import {formatDateTime} from '@/util/formatTime.js'
import * as iotTokenApi from '@/api/iot/iotTokenApi.js'
import * as clipboard from '@/util/clipboard.js'
import * as authTokenApi from '@/api/auth/authTokenApi.js'
import * as storage from '@/util/storage.js'

import {
	showToast
} from '@/util/toast.js'

let count = 0;
export function incr(){
	count = count + 1
	return count
}

export function copy(that, text) {
	// #ifdef H5
	clipboard.handleClipboard(text, event, () => {
		showToast(that.$t('copy') + that.$t('success'))
	})
	// #endif
	// #ifndef H5
	uni.setClipboardData({
		data: text,
		success: () => {
			showToast(that.$t('copy') + that.$t('success'))
		}
	})
	// #endif
}

export function parseUrl(url) {
	let result = [];
	let query = url.split('?')[1];
	if (query == null) {
		return null
	}
	let obj = {};
	let queryArr = query.split('&');
	if (queryArr.length < 1) {
		let split = query.split('=')
		let key = split[0];
		let value = split[1];
		obj[key] = value;
	} else {
		queryArr.forEach(function(item) {
			let split = item.split('=')
			let key = split[0];
			let value = split[1];
			obj[key] = value;
		});
	}
	return obj;
}

export function commonScanHandle(that, res) {
	const param = parseUrl(res);
	if (param != null && param.deviceCore) {
		try {
			showToast(that.$t('success'), 'success', 1000, false) //操作成功
			uni.navigateTo({
				url: `/pages/deviceNavigation/deviceNavigation?deviceCore=${param.deviceCore}&name=${param.name}&command=${param.function}&keyName=${param.keyName}&value=${param.value}&port=${param.port}&component=deviceInfo`
			});
		} catch (e) {
			showToast(that.$t('qrcode') + that.$t('error'), 'none', 1000,
				false) //二维码有误
		}
	} else {
		showToast(that.$t('qrcode') + that.$t('error'), 'none', 1000, false) //二维码有误
	}

}

export function listProductList(that, data) {
	const productList = [{
		productId: null,
		name: that.$t('all') + that.$t('product')
	}]
	for (let i = 0; i < data.length; i++) {
		const item = data[i]
		productList.push({
			productId: item.productId,
			name: item.name
		});
	}
	return productList
}

export function listProductSeries(that, data) {
	const productSeriesList = [{
		seriesId: null,
		name: that.$t('all') + that.$t('series')
	}]
	for (let i = 0; i < data.length; i++) {
		const item = data[i]
		productSeriesList.push({
			seriesId: item.seriesId,
			name: item.name
		});
	}
	return productSeriesList
}

export function listDeviceStatus(that) {
	return [{
			label: that.$t('all') + that.$t('status'),
			value: ''
		},
		{
			label: that.$t('ONLINE'),
			value: 'ONLINE'
		},
		{
			label: that.$t('OFFLINE'),
			value: 'OFFLINE'
		},
		{
			label: that.$t('DISABLE'),
			value: 'DISABLE'
		},
		{
			label: that.$t('UNACTIVE'),
			value: 'UNACTIVE'
		}
	]
}

export function listWorkOrderStatus(that) {
	return [{
			value: 0,
			label: that.$t('untreated')
		},
		{
			value: 1,
			label: that.$t('misinformation')
		},
		{
			value: 2,
			label: that.$t('processed')
		}
	]
}

export function formatWorkOrderStatus(that, status) {
	const list = listWorkOrderStatus(that)
	for (const item of list) {
		if (item.value === status) {
			return item.label
		}
	}
}

export function formatDeviceStatus(that, status) {
	if (!status) {
		return that.$t('all')
	}
	const list = listDeviceStatus(that)
	for (const item of list) {
		if (item.value === status) {
			return item.label
		}
	}
}

export function urlSearch() {
	let name, value;
	// let str = 'http://iot.ztn-tech.com/m/index.html?companyId=2#/pages/login/login'
	let str = window.location.href; //取得整个地址栏
	let startIndex = str.indexOf('?')
	let endIndex = str.indexOf('#')
	str = str.substr(startIndex + 1, endIndex - 1 - startIndex); //取得所有参数   stringvar.substr(start [, length ]

	let arr = str.split('&'); //各个参数放到数组里
	for (let i = 0; i < arr.length; i++) {
		startIndex = arr[i].indexOf('=');
		if (startIndex > 0) {
			name = arr[i].substring(0, startIndex);
			value = arr[i].substr(startIndex + 1);
			this[name] = value;
		}
	}
}

export function getPages() {
	return getCurrentPages();
}

export function getPrevPage() {
	const pages = getPages()
	const prevPage = pages[pages.length - 2];
	return prevPage
}

export function formatPhoneStatus(that, status) {
	switch (status) {
		case 1:
			return that.$t('toBeActivated')
		case 2:
			return that.$t('silentPeriod')
		case 3:
			return that.$t('testingPeriod')
		case 4:
			return that.$t('normal')
		case 5:
			return that.$t('shutdown')
		case 6:
			return that.$t('cancelledNumber')
		default:
			return that.$t('unKnow')
	}
}

export function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

export function checkLogin() {
	return new Promise((resolve, reject) => {
		const accessToken = storage.getToken()
		if (!accessToken) {
			reject()
			uni.reLaunch({
				url: '/pages/login/login'
			})
		} else {
			authTokenApi.checkLogin().then(res => {
				const {
					data
				} = res
				if (data) {
					resolve(data)
				} else {
					reject()
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}
			})
		}
	})

}

export function formatSettingList(data) {
	const list = []
	for (let i = 0, j = data.length; i < j; i++) {
		const item = data[i]
		list.push(formatSetting(item))
	}
	return list
}

export function formatSetting(item) {
	if (item.type == 'switch') {
		item.value = item.value == 1 ? true : false
	} else if (item.type == 'timeSlot') {
		if (item.value && item.value.indexOf(' / ') != -1) {
			const value = item.value.split(' / ');
			const fvalue = value[0].split(':');
			const svalue = value[1].split(':');
			item.timeSlotMultiIndex = fvalue.concat(svalue)
			item.value = fvalue.map(formatNumber).join(':') + ' / ' + svalue.map(
				formatNumber).join(':')
		} else {
			item.timeSlotMultiIndex = [0, 0, 0, 0]
		}
	} else if (item.type == 'multiCustom') {
		const valueList = []
		const valueSplitList = item.value
		for (let i = 0, j = valueSplitList.length; i < j; i++) {
			const typeRule = item.typeRuleList[i] || 'custom'
			const value = valueSplitList[i]

			const valueItem = {
				value: value,
				type: typeRule,
				valueIndex: 0
			}
			if (typeRule == 'switch') {
				valueItem.value = value === '1' ? true : false
			} else if (typeRule === 'fixedParam') {
				for (let i = 0, j = item.paramList.length; i < j; i++) {
					if (item.paramList[i].value === value) {
						valueItem.valueIndex = i
					}
				}
			} else if (typeRule === 'timeSlot') {
				if (value.indexOf(' / ') != -1) {
					const timeValue = value.split(' / ');
					const fvalue = timeValue[0].split(':');
					const svalue = timeValue[1].split(':');
					valueItem.timeSlotMultiIndex = fvalue.concat(svalue)
					valueItem.value = fvalue.map(formatNumber).join(':') + ' / ' + svalue.map(formatNumber).join(':')
				} else {
					valueItem.timeSlotMultiIndex = [0, 0, 0, 0]
				}
			}
			valueList.push(valueItem)
		}
		item.valueList = valueList
	}
	if (item.name.length > 8 || item
		.remark.length > 8 || (item.type !== 'switch' && item.type !==
			'noParam' && item
			.type !== 'time' && item
			.type !== 'timeSlot')) {
		item.isFullLine = true
	} else {
		item.isFullLine = false
	}
	return item
}
